package com.micro.business.admin.service.impl;

import com.micro.business.admin.config.redis.RedisTemplateManager;
import com.micro.business.admin.service.UmsMemberService;
import com.micro.business.common.api.CommonResult;
import com.micro.business.common.util.Check;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * <P>会员管理Service实现</P>
 *
 * @author 高仕立
 * @date 2019/8/2 9:03 AM
 * @since
 */
@Service
@Slf4j
public class UmsMemberServiceImpl implements UmsMemberService {
    @Autowired
    private RedisTemplateManager redisTemplateManager;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    /**
     * 获取验证码
     *
     * @param telephone
     * @return com.micro.business.common.api.CommonResult
     * @author 高仕立
     * @since 2019/8/2 09:06
     */
    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        //验证码绑定手机号并存储到redis
        redisTemplateManager.setObject(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
        redisTemplateManager.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(sb.toString(), "获取验证码成功");
    }


    /**
     * 对输入的验证码进行校验
     *
     * @param telephone
     * @param authCode
     * @return com.micro.business.common.api.CommonResult
     * @author 高仕立
     * @since 2019/8/2 09:06
     */
    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        log.info("--对输入的验证码进行校验--telephone:{},authCode:{}",telephone,authCode);
        if (Check.isEmpty(telephone)) {
            return CommonResult.failed("请输入验证码");
        }
        String realAuthCode = redisTemplateManager.getString(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        boolean result = authCode.equals(realAuthCode);
        if (result) {
            return CommonResult.success(null, "验证码校验成功");
        } else {
            return CommonResult.failed("验证码不正确");
        }
    }

}